package com.masterlu.executor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author：masterlu
 * @Date：2021/3/26 9:16 下午
 */
public class ExecutorDemo {
    public static void main(String[] args) {


        int count = 10;
        CountDownLatch latch = new CountDownLatch(count);
        AtomicInteger atomicInteger = new AtomicInteger(0);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                4,
                300,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(5),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("test Thread"+atomicInteger.incrementAndGet());
                    return thread;
                },
                (r, executor1) -> {
                    System.out.println("拒绝策略，可以保存到数据库中"+Thread.currentThread().getName());
                    r.run();

                });
        executor.prestartAllCoreThreads();


        for (int i = 0;i < 10;i++){
            executor.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println("----------");
                    System.out.println(Thread.currentThread().getName());
                    latch.countDown();
                } catch (Exception e) {
                    System.err.println("异常了"+e);
                }
                System.out.println("队列长度:"+executor.getQueue().size()+"latch count:"+latch.getCount());
            });

        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}
